<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="中继编码" prop="deviceRelayCode">
        <el-input
          v-model="queryParams.deviceRelayCode"
          placeholder="请输入设备中继编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
          <el-option label="TCP设备" value="TCP" />
          <el-option label="RTU设备" value="RTU" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
          <el-option label="故障" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:device:remove']"
        >删除</el-button>
      </el-col>
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange" :default-sort="{prop: 'deviceId', order: 'ascending'}">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="ID" align="center" prop="deviceId" width="50" />
      <el-table-column label="名称" align="center" prop="deviceName" />
      <el-table-column label="中继编码" align="center" prop="deviceRelayCode" />
      <el-table-column label="类型" align="center" prop="deviceType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.deviceType === 'TCP'" type="success">TCP</el-tag>
          <el-tag v-else-if="scope.row.deviceType === 'RTU'" type="warning">RTU</el-tag>
          <span v-else>{{ scope.row.deviceType }}</span>
        </template>
      </el-table-column>
      <!-- TCP设备显示网络信息 -->
      <el-table-column label="IP地址" align="center" prop="ipAddress" width="140" v-if="showTcpColumns">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceType === 'TCP'">{{ scope.row.ipAddress }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="端口号" align="center" prop="port" v-if="showTcpColumns">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceType === 'TCP'">{{ scope.row.port }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      
      <!-- RTU设备显示串口信息 -->
      <el-table-column label="串口号" align="center" prop="serialPort" v-if="showRtuColumns">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceType === 'RTU'">{{ scope.row.serialPort }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="波特率" align="center" prop="baudRate" v-if="showRtuColumns">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceType === 'RTU'">{{ scope.row.baudRate }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="数据位" align="center" prop="dataBits" v-if="showRtuColumns">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceType === 'RTU'">{{ scope.row.dataBits }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="停止位" align="center" prop="stopBits" v-if="showRtuColumns">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceType === 'RTU'">{{ scope.row.stopBits }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="校验位" align="center" prop="parity" v-if="showRtuColumns">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.deviceType === 'RTU' && scope.row.parity === 'NONE'" type="info">无校验</el-tag>
          <el-tag v-else-if="scope.row.deviceType === 'RTU' && scope.row.parity === 'ODD'" type="warning">奇校验</el-tag>
          <el-tag v-else-if="scope.row.deviceType === 'RTU' && scope.row.parity === 'EVEN'" type="warning">偶校验</el-tag>
          <el-tag v-else-if="scope.row.deviceType === 'RTU' && scope.row.parity === 'MARK'" type="danger">标记校验</el-tag>
          <el-tag v-else-if="scope.row.deviceType === 'RTU' && scope.row.parity === 'SPACE'" type="danger">空格校验</el-tag>
          <span v-else-if="scope.row.deviceType === 'RTU'">{{ scope.row.parity }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="槽数" align="center" prop="slotCount" />
      <el-table-column label="每槽点数" align="center" prop="pointsPerSlot" />
      <el-table-column label="起始槽号" align="center" prop="startSlotNumber" />
      <el-table-column label="终止槽号" align="center" prop="endSlotNumber" />
      <el-table-column label="设备状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status === '1'" type="danger">停用</el-tag>
          <el-tag v-else-if="scope.row.status === '2'" type="danger">故障</el-tag>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:device:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[6, 10, 20, 50]"
      :layout="'total, sizes, prev, pager, next, jumper'"
      @pagination="getList"
    />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备中继编码" prop="deviceRelayCode">
              <el-input v-model="form.deviceRelayCode" placeholder="请输入设备中继编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="form.deviceType" placeholder="请选择设备类型" @change="handleDeviceTypeChange">
                <el-option label="TCP设备" value="TCP"></el-option>
                <el-option label="RTU设备" value="RTU"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择设备状态">
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
                <el-option label="故障" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- TCP设备网络配置 -->
        <el-row v-if="form.deviceType === 'TCP'">
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口号" prop="port">
              <el-input v-model="form.port" placeholder="请输入端口号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- RTU设备串口配置 -->
        <el-row v-if="form.deviceType === 'RTU'">
          <el-col :span="12">
            <el-form-item label="串口号" prop="serialPort">
              <el-input v-model="form.serialPort" placeholder="请输入串口号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="波特率" prop="baudRate">
              <el-input v-model="form.baudRate" placeholder="请输入波特率" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.deviceType === 'RTU'">
          <el-col :span="12">
            <el-form-item label="数据位" prop="dataBits">
              <el-input v-model="form.dataBits" placeholder="请输入数据位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="停止位" prop="stopBits">
              <el-input v-model="form.stopBits" placeholder="请输入停止位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.deviceType === 'RTU'">
          <el-col :span="12">
            <el-form-item label="校验位" prop="parity">
              <el-select v-model="form.parity" placeholder="请选择校验位">
                <el-option label="无校验" value="NONE"></el-option>
                <el-option label="奇校验" value="ODD"></el-option>
                <el-option label="偶校验" value="EVEN"></el-option>
                <el-option label="标记校验" value="MARK"></el-option>
                <el-option label="空格校验" value="SPACE"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="槽数" prop="slotCount">
              <el-input v-model="form.slotCount" placeholder="请输入槽数" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 通用配置 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="槽数" prop="slotCount">
              <el-input v-model="form.slotCount" placeholder="请输入槽数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每槽点数" prop="pointsPerSlot">
              <el-input v-model="form.pointsPerSlot" placeholder="请输入每槽点数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="槽偏移量" prop="slotOffset">
              <el-input v-model="form.slotOffset" placeholder="请输入槽偏移量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起始槽号" prop="startSlotNumber">
              <el-input v-model="form.startSlotNumber" placeholder="请输入起始槽号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="终止槽号" prop="endSlotNumber">
              <el-input v-model="form.endSlotNumber" placeholder="请输入终止槽号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/business/device";

export default {
  name: "Device",
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 6,
        deviceRelayCode: null,
        deviceType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        deviceRelayCode: [
          { required: true, message: "设备中继编码不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    // 是否显示TCP相关列
    showTcpColumns() {
      return this.deviceList.some(device => device.deviceType === 'TCP');
    },
    // 是否显示RTU相关列
    showRtuColumns() {
      return this.deviceList.some(device => device.deviceType === 'RTU');
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      console.log('查询参数:', this.queryParams);
      listDevice(this.queryParams).then(response => {
        console.log('响应数据:', response);
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceName: null,
        deviceRelayCode: null,
        deviceType: null,
        ipAddress: null,
        port: null,
        serialPort: null,
        baudRate: null,
        dataBits: null,
        stopBits: null,
        parity: null,
        slotCount: null,
        pointsPerSlot: null,
        slotOffset: null,
        startSlotNumber: null,
        endSlotNumber: null,
        status: "0",
        lastCommTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除设备信息编号为"' + deviceIds + '"的数据项？').then(function() {
        return delDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /** 设备类型变化处理 */
    handleDeviceTypeChange(value) {
      // 当设备类型改变时，清空相关字段
      if (value === 'TCP') {
        // TCP设备清空串口相关字段
        this.form.serialPort = '';
        this.form.baudRate = '';
        this.form.dataBits = '';
        this.form.stopBits = '';
        this.form.parity = '';
      } else if (value === 'RTU') {
        // RTU设备清空网络相关字段
        this.form.ipAddress = '';
        this.form.port = '';
      }
    }
    
  }
};
</script>
